// File:    TnExToolsDataManager.cs
// Author:  HT
// Created: Saturday, October 22, 2011 12:21:44 AM
// Purpose: Definition of Class TnExToolsDataManager

using System;
using System.Data;
using System.Data.SqlClient;
using ESRI.ArcGIS.Geoprocessor;
using ESRI.ArcGIS.DataManagementTools;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.DataSourcesGDB;
using System.Windows.Forms;



namespace Tayninh2011
{
   public class TnExToolsDataManager : TnExtensionTools, ITnExToolsDataManager,ITnRelationships
   {
       
       //constructor
       private static int num = 0;
       public TnExToolsDataManager()
       {
           
       }

       string ITnExToolsDataManager.TnCreateFeatureLayer(string inFeature, string outLayer, string environment, string dieukien)
      {
          Geoprocessor GP = new Geoprocessor();
          //MessageBox.Show(dieukien);
          // Intialize the MakeFeatureLayer tool
          GP.SetEnvironmentValue("workspace", environment);
          MakeFeatureLayer makefeaturelayer = new MakeFeatureLayer();

          makefeaturelayer.in_features = inFeature;
          makefeaturelayer.out_layer = outLayer;
          runTool(GP, makefeaturelayer, null);

          SelectLayerByAttribute SelectByAttribute = new SelectLayerByAttribute();
          GP.ResetEnvironments();
          SelectByAttribute.in_layer_or_view = outLayer;
          SelectByAttribute.selection_type = "NEW_SELECTION";
          SelectByAttribute.where_clause = dieukien;
          runTool(GP, SelectByAttribute, null);


          CopyFeatures copyFeatures = new CopyFeatures();
          
          copyFeatures.in_features = outLayer;
          
          copyFeatures.out_feature_class = this.Mem4DataManager.TempFullPath+"copiedFeature";

          // Set the output Coordinate System environment
          //GP.SetEnvironmentValue("outputCoordinateSystem",
          //@"C:\Program Files\ArcGIS\Coordinate Systems\Projected Coordinate Systems\UTM\Nad 1983\NAD 1983 UTM Zone 21N.prj");

          runTool(GP, copyFeatures, null);
          return this.Mem4DataManager.TempFullPath+"copiedFeature";
      }

       string ITnExToolsDataManager.TnCreateFeatureLayer(string inFeature, string outLayer, string dieukien)
       {
           //num++;
           Geoprocessor GP = new Geoprocessor();
           //MessageBox.Show(dieukien);
           // Intialize the MakeFeatureLayer tool
           //GP.SetEnvironmentValue("workspace", environment);
           MakeFeatureLayer makefeaturelayer = new MakeFeatureLayer();

           makefeaturelayer.in_features = inFeature;//this.Mem4DataManager.TempFullPath + inFeature;
           makefeaturelayer.out_layer = this.Mem4DataManager.TempFullPath+outLayer;
           runTool(GP, makefeaturelayer, null);

           SelectLayerByAttribute SelectByAttribute = new SelectLayerByAttribute();
           GP.ResetEnvironments();
           SelectByAttribute.in_layer_or_view = this.Mem4DataManager.TempFullPath+outLayer;
           SelectByAttribute.selection_type = "NEW_SELECTION";
           SelectByAttribute.where_clause = dieukien;
           runTool(GP, SelectByAttribute, null);


           CopyFeatures copyFeatures = new CopyFeatures();

           copyFeatures.in_features = outLayer;

           copyFeatures.out_feature_class = this.Mem4DataManager.TempFullPath + "copiedFeature";

           // Set the output Coordinate System environment
           //GP.SetEnvironmentValue("outputCoordinateSystem",
           //@"C:\Program Files\ArcGIS\Coordinate Systems\Projected Coordinate Systems\UTM\Nad 1983\NAD 1983 UTM Zone 21N.prj");

           //runTool(GP, copyFeatures, null);
           GP.Execute(copyFeatures, null);
           return this.Mem4DataManager.TempFullPath + "copiedFeature" ;
       }

       void ITnExToolsDataManager.TnCreateFeatureLayer(string inFeature, string outLayer, string dieukien,out string out_featureClass)
       {
           //num++;
           Geoprocessor GP = new Geoprocessor();
           //MessageBox.Show(dieukien);
           // Intialize the MakeFeatureLayer tool
           //GP.SetEnvironmentValue("workspace", environment);
           MakeFeatureLayer makefeaturelayer = new MakeFeatureLayer();
           
           //MessageBox.Show(inFeature);
           makefeaturelayer.in_features = this.Mem4DataManager.TempFullPath+inFeature; //"C:/tayninh/temp/tempmdb.mdb/tntn_hem_buff_1";
           makefeaturelayer.out_layer = "outlayer";//"C:/tayninh/temp/tempmdb.mdb/ot";//this.Mem4DataManager.TempFullPath+"tn" + outLayer;
           runTool(GP, makefeaturelayer, null);

           SelectLayerByAttribute SelectByAttribute = new SelectLayerByAttribute();
           GP.ResetEnvironments();
           SelectByAttribute.in_layer_or_view = "outlayer";//"C:/tayninh/temp/tempmdb.mdb/ot"; //this.Mem4DataManager.TempFullPath + "tn" + outLayer;
           SelectByAttribute.selection_type = "NEW_SELECTION";
           SelectByAttribute.where_clause = dieukien;
           runTool(GP, SelectByAttribute, null);


           CopyFeatures copyFeatures = new CopyFeatures();

           copyFeatures.in_features = "outlayer";

           copyFeatures.out_feature_class = this.Mem4DataManager.TempFullPath + "tn" + "cop";// + TnFeatureClassName.HEM_BUFFER_1M_CREATED_FROM_LAYER;

           // Set the output Coordinate System environment
           //GP.SetEnvironmentValue("outputCoordinateSystem",
           //@"C:\Program Files\ArcGIS\Coordinate Systems\Projected Coordinate Systems\UTM\Nad 1983\NAD 1983 UTM Zone 21N.prj");

           //runTool(GP, copyFeatures, null);
           GP.Execute(copyFeatures, null);
           out_featureClass = this.Mem4DataManager.TempFullPath + "tn" + "cop";// + TnFeatureClassName.HEM_BUFFER_1M_CREATED_FROM_LAYER;
       }

       //IFeatureClass ITnExToolsDataManager.TnOpenFeatureClassFromFileMdb(string pathNoEnd, string name)
       //{
       //    IWorkspaceFactory2 mdbWspf = new AccessWorkspaceFactoryClass();
       //    IWorkspace wsp;
       //    IFeatureWorkspace fwsp;

       //    wsp = mdbWspf.OpenFromFile(pathNoEnd, 0);
       //    fwsp = (IFeatureWorkspace)wsp;
       //    return fwsp.OpenFeatureClass(name);
       //}

       IFeatureClass ITnExToolsDataManager.TnOpenFeatureClassFromFileMdb(params string[] fullpathOrPathandname)
       {
           IWorkspaceFactory2 mdbWspf = new AccessWorkspaceFactoryClass();
           IWorkspace wsp;
           IFeatureWorkspace fwsp;
           int i = fullpathOrPathandname.Length;
           string pathNoEnd = "";
           string name = "";
           int j = 0;
           if (i == 2)
           {
               pathNoEnd = fullpathOrPathandname[0];
               name = fullpathOrPathandname[1];
           }
           else if(i==1)
           {
               for (j = fullpathOrPathandname[0].Length-1; j > 0; j--)
               {
                   if (fullpathOrPathandname[0][j].CompareTo(System.Char.Parse("/"))==0)
                   {
                       break;
                   }
               }
               pathNoEnd = fullpathOrPathandname[0].Substring(0, j);
               name = fullpathOrPathandname[0].Substring(j + 1, fullpathOrPathandname[0].Length - 1 - j);
           }
           wsp = mdbWspf.OpenFromFile(pathNoEnd, 0);
           fwsp = (IFeatureWorkspace)wsp;
           return fwsp.OpenFeatureClass(name);
       }

       IFeatureClass ITnExToolsDataManager.TnOpenFeatureClassFromSDE(IWorkspaceEdit workspace, string featureClass)
       {
           IFeatureWorkspace fwsp = (IFeatureWorkspace)workspace;
           return fwsp.OpenFeatureClass(featureClass);
       }

       ITable ITnExToolsDataManager.OpenTableFromSDE(IWorkspaceEdit workspace, string table)
       {
           IFeatureWorkspace fwsp = (IFeatureWorkspace)workspace;
           return fwsp.OpenTable(table);
       }

       bool ITnExToolsDataManager.TnCheckLayerExist(string[,] user_info, string layer_name)
       {
           string strConnection = "";
           string sql = "SELECT * FROM sde.sde.SDE_layers WHERE table_name='" + layer_name + "'";

           for (int i = 0; i < user_info.Length / 2; i++)
           {
               strConnection += user_info[i, 0] + "=" + user_info[i, 1];
               strConnection += ";";
           }
           SqlConnection conn = new SqlConnection(strConnection);
           SqlCommand cmd = new SqlCommand(sql, conn);
           conn.Open();
           SqlDataReader reader = cmd.ExecuteReader();
           int a = 0;
           while (reader.Read())
           {
               a++;
           }
           if (reader.HasRows)
           {
               //MessageBox.Show(a.ToString());
               return true;
           }
           else
           {
               //MessageBox.Show(reader.HasRows.ToString());
               return false;
           }
       }

       DataSet ITnExToolsDataManager.TnQueryBySQL(string[,] userInfo, string dieukien)
       {
           string connetionString = null;
           SqlConnection connection;
           SqlCommand command;
           SqlDataAdapter adapter = new SqlDataAdapter();
           DataSet ds = new DataSet();
           
           int i = 0;
           string sql = null;
           if (userInfo != null)
           {
               for (int j = 0; j < userInfo.Length / 2; j++)
               {
                   connetionString += userInfo[j, 0] + "=" + userInfo[j, 1];
                   connetionString += ";";
               }
           }
           else
           {
               connetionString = "server=localhost;Trusted_Connection=yes;";
           }
           //connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
           //sql = "select * from tn_thua";
           sql = dieukien;

           connection = new SqlConnection(connetionString);

           try
           {
               connection.Open();
               
               //RootForm.Sqlconnection.Open();
               command = new SqlCommand(sql, connection);
               adapter.SelectCommand = command;
               adapter.Fill(ds);
               adapter.Dispose();
               command.Dispose();
               connection.Close();
               
               //this.dgvTable.DataSource = ds.Tables[0];


               //for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
               //{
               //    MessageBox.Show(ds.Tables[0].Rows[i].ItemArray[0] + " -- " + ds.Tables[0].Rows[i].ItemArray[1]);

               //}
           }
           catch (Exception ex)
           {
               return null;
           }
           return ds;
       }

       bool ITnExToolsDataManager.TnUpdateBySQL(string[,] userInfo, string sql)
       {
           string connetionString = null;
           SqlConnection connection;
           SqlCommand command;
           

           int i = 0;
           string sqlCmd = null;
           for (int j = 0; j < userInfo.Length / 2; j++)
           {
               connetionString += userInfo[j, 0] + "=" + userInfo[j, 1];
               connetionString += ";";
           }
           //connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
           //sql = "select * from tn_thua";
           sqlCmd = sql;
           
           connection = new SqlConnection(connetionString);

           try
           {
               connection.Open();
               command = new SqlCommand(sqlCmd, connection);
               command.ExecuteNonQuery();
               command.Dispose();
               connection.Close();

               //this.dgvTable.DataSource = ds.Tables[0];


               //for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
               //{
               //    MessageBox.Show(ds.Tables[0].Rows[i].ItemArray[0] + " -- " + ds.Tables[0].Rows[i].ItemArray[1]);

               //}
           }
           catch
           {
               return false;
           }
           return true;
       }


       #region ITnRelationships Members

       ISet ITnRelationships.GetRelatedObjectSet(IRelationshipClass relationShipClass, IFeatureClass fc, string dieukien)
       {
           ISet inputObject = new SetClass();
           ISet relatedObject = new SetClass();
           IRelClassEnumRowPairs row=null;
           try
           {
               IQueryFilter qf = new QueryFilterClass();
               IFeatureCursor fcr = fc.Search(qf, false);
               IFeature ft = fcr.NextFeature();
               while (ft != null)
               {
                   inputObject.Add(ft);
                   ft = fcr.NextFeature();
               }
               relatedObject = relationShipClass.GetObjectsRelatedToObjectSet(inputObject);
               row = relationShipClass.GetObjectsMatchingObjectSet(relatedObject);
           }
           catch { }
           return relatedObject;
       }

       IRelClassEnumRowPairs ITnRelationships.GetPairRelatedObjects(IRelationshipClass relationShipClass, IFeatureClass fc, string dieukien)
       {
           ISet inputObject = new SetClass();
           ISet relatedObject = new SetClass();
           IRelClassEnumRowPairs row = null;
           try
           {
               IQueryFilter qf = new QueryFilterClass();
               IFeatureCursor fcr = fc.Search(qf, false);
               IFeature ft = fcr.NextFeature();
               while (ft != null)
               {
                   inputObject.Add(ft);
                   ft = fcr.NextFeature();
               }
               relatedObject = relationShipClass.GetObjectsRelatedToObjectSet(inputObject);
               row = relationShipClass.GetObjectsMatchingObjectSet(relatedObject);
           }
           catch { }
           return row;
       }

       IRelClassEnumRowPairs ITnRelationships.GetPairRelatedObjects(IRelationshipClass relationShipClass, ITable table, string dieukien)
       {
           ISet inputObject = new SetClass();
           ISet relatedObject = new SetClass();
           IRelClassEnumRowPairs row = null;
           try
           {
               IQueryFilter qf = new QueryFilterClass();
               ICursor fcr = table.Search(qf, false);
               IRow r = fcr.NextRow();
               while (r != null)
               {
                   inputObject.Add(r);
                   r = fcr.NextRow();
               }
               relatedObject = relationShipClass.GetObjectsRelatedToObjectSet(inputObject);
               row = relationShipClass.GetObjectsMatchingObjectSet(relatedObject);
           }
           catch { }
           return row;
       }

       IRelationshipClass ITnRelationships.OpenRelationShipClass(string name, IWorkspaceEdit workspace)
       {
           IFeatureWorkspace fw = (IFeatureWorkspace)workspace;
           IRelationshipClass rc = null;
           try
           {
               rc = fw.OpenRelationshipClass(name);
           }
           catch { }
           return rc;
       }

       #endregion
   }
}
